<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 12/26/2014
 * Time: 11:31 AM
 */
namespace BC\Games\Holdem;

use BC\User\Service\TestUser;
use CPath\Request\IRequest;

class TestHoldemPlayer extends TestUser
{
	public function __construct(IRequest $Request, $username = null, $passphrase = null) {
		parent::__construct($Request, 'holdem-round-player-' . $username, $passphrase);
	}

	public function doAction(IRequest $Request, HoldemRound $Round) {
		$playerID = $this->getUserID();
		$Player   = $Round->getPlayer($playerID);
		if(!$Round->hasStarted()) {
			if(!$Player->isReady())
				$Round->ready($Request, $playerID);
			return;
		}
		$curBet   = $Round->getCurrentBetAmount();
		if ($Player->hasFolded())
			return;
		$err = null;
		if ($Round->hasMove($playerID, $err)) {
			if ($curBet > $Player->getBetAmount()) {
				if (rand(0, 1000) % 3 === 2)
					$Round->fold($Request, $playerID);
				else
					$Round->call($Request, $playerID);
			} else {
				$canBet = $Player->getBalance() > $curBet;
				if (rand(0, 1000) % 5 !== 3)
					$canBet = false;

				if ($canBet)
					$Round->raise($Request, $playerID, rand(0, $Player->getRemainingBalance()));
				else
					$Round->check($Request, $playerID);
			}
		}
		if ($Round->hasMove($playerID, $err)) {
			if(!$Player->hasChecked())
				$Player->check();
			if ($Round->hasMove($playerID, $err))
				throw new \Exception("Player didn't finish move: " . $err);
		}
	}
}